//  npx ts-node -r tsconfig-paths/register ./src/scripts/import-food.ts

import { DataSource } from 'typeorm';
import { Food, Category } from '@/modules/app/entities';
import * as XLSX from 'xlsx';
import * as path from 'path';
import pinyin from 'pinyin';

// const HOST = '127.0.0.1';
const HOST = '8.134.250.251';
const AppDataSource = new DataSource({
  type: 'mysql',
  host: HOST,
  username: 'root',
  port: 3309,
  password: 'Respect2727259150.',
  // port: 3306,
  // password: '',
  database: 'diet',
  entities: [path.join(__dirname, '../modules/**/*.entity{.ts,.js}')],
  synchronize: false,
  logging: false,
});

// === 营养元素类型 ===
enum NutrientType {
  CALORIES = 'CALORIES',
  CARBS = 'CARBS',
  PROTEIN = 'PROTEIN',
  CHOLESTEROL = 'CHOLESTEROL',
  FAT = 'FAT',
  FIBER = 'FIBER',
  FOLATE = 'FOLATE',
  IRON = 'IRON',
  MAGNESIUM = 'MAGNESIUM',
  VITAMIN_B12 = 'VITAMINB12',
  VITAMIN_B6 = 'VITAMINB6',
  BETA_CAROTENE = 'BETACAROTENE',
  MUFA = 'MUFA',
  NIACIN = 'NIACIN',
  OMEGA3 = 'OMEGA3',
  PUFA = 'PUFA',
  RIBOFLAVIN = 'RIBOFLAVIN',
  SFA = 'SFA',
  SELENIUM = 'SELENIUM',
  THIAMINE = 'THIAMINE',
  VITAMIN_A = 'VITAMINA',
  VITAMIN_C = 'VITAMINC',
  VITAMIN_D = 'VITAMIND',
  VITAMIN_E = 'VITAMINE',
  ZINC = 'ZINC',
}

const headerToNutrientType = {
  '热量（千卡）': NutrientType.CALORIES,
  '碳水化合物（克）': NutrientType.CARBS,
  '蛋白质（克）': NutrientType.PROTEIN,
  '胆固醇（毫克）': NutrientType.CHOLESTEROL,
  '脂肪（克）': NutrientType.FAT,
  '纤维素（g）': NutrientType.FIBER,
  '叶酸（μg）': NutrientType.FOLATE,
  '铁（mg）': NutrientType.IRON,
  '镁（mg）': NutrientType.MAGNESIUM,
  '维生素 B12（μg）': NutrientType.VITAMIN_B12,
  '维生素 B6（mg）': NutrientType.VITAMIN_B6,
  'β-胡萝卜素（μg）': NutrientType.BETA_CAROTENE,
  '单不饱和脂肪酸（g）': NutrientType.MUFA,
  '烟酸（mg）': NutrientType.NIACIN,
  'n-3 脂肪酸（g）': NutrientType.OMEGA3,
  '多不饱和脂肪酸（g）': NutrientType.PUFA,
  '核黄素（mg）': NutrientType.RIBOFLAVIN,
  '饱和脂肪酸（g）': NutrientType.SFA,
  '硒（μg）': NutrientType.SELENIUM,
  '硫胺（mg）': NutrientType.THIAMINE,
  '维生素 A（μg）': NutrientType.VITAMIN_A,
  '维生素 C（mg）': NutrientType.VITAMIN_C,
  '维生素 D（μg）': NutrientType.VITAMIN_D,
  '维生素 E（mg）': NutrientType.VITAMIN_E,
  '锌（mg）': NutrientType.ZINC,
};

function getFileJSON(fileName: string, sheet: number = 0) {
  const rootDir = path.resolve(__dirname, './template/');
  const filePath = path.join(rootDir, fileName);

  const workbook = XLSX.readFile(filePath);
  const firstSheetName = workbook.SheetNames[sheet];
  const worksheet = workbook.Sheets[firstSheetName];

  const data = XLSX.utils.sheet_to_json(worksheet) as any[];
  return data;
}

const main = async () => {
  await AppDataSource.initialize();
  const foodRepo = AppDataSource.getRepository(Food);
  const categoryRepo = AppDataSource.getRepository(Category);

  const yanzhengData = getFileJSON('yanzheng.xlsx');
  const yanzhengResult = {};
  for (const item of Object.keys(yanzhengData[0])) {
    if (item.includes('__EMPTY')) continue;
    yanzhengResult[item] = parseFloat(yanzhengData[0][item]);
  }

  const sheet = [0];
  for (const s of sheet) {
    const foodData = getFileJSON('food.xlsx', s);
    for (const re of foodData) {
      let food = await foodRepo.findOne({
        where: {
          name: re['菜名'],
        },
      });
      // if (food) {
      //   console.log('食物已存在', re['菜名']);
      //   continue;
      // }

      // if (!re['种类']) {
      //   console.log(re['种类'], '缺少种类');
      //   continue;
      // }

      let category = await categoryRepo.findOne({
        where: {
          categoryName: re['种类'],
        },
      });

      if(category){
        console.log('更新分类', category.categoryId, re['分类']);
        await categoryRepo.update(category.categoryId, {
          tag: re['分类'],
        })
      }

      if (!category) {
        console.log(`创建新种类: ${re['种类']}`);
        category = await categoryRepo.save({
          categoryName: re['种类'],
        });
      }

      // const params = {
      //   name: re['菜名'].trim(),
      //   imageUrl: `/static/${pinyin(re['菜名'].trim(), { style: 'normal', heteronym: false }).join('')}.png`,
      //   categoryId: category.categoryId,
      //   microElement: [] as any[],
      //   tag: re['分类'],
      // };

      // for (const ele of Object.keys(re)) {
      //   if (!headerToNutrientType[ele]) continue;
      //   const micro = {
      //     type: headerToNutrientType[ele],
      //     amount: parseFloat(re[ele]),
      //     inflammationIndex: yanzhengResult[ele],
      //     unit: ele.match(/\（(.*?)\）/)?.[1],
      //   };
      //   params.microElement.push(micro);
      // }

      // await foodRepo.save(params);
      // console.log('成功添加：', params.name);
    }
  }

  process.exit(0);
};

main();
